package org.concepts.algorithm.datastructure;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Simple {@link Node} in the {@link Tree}. This class is not thread safe.
 * 
 * @author vvvv
 * 
 */
public class SimpleNode<V> implements Node<V> {

  private List<Node<V>> children = null;
  private Node<V> parent = null;
  private V value = null;
  private static AtomicInteger idGen = new AtomicInteger(0);
  private int id;

  @Override
  public String toString() {
    StringBuilder str = new StringBuilder();
    str.append("Node id: " + id + " parentId: "
        + ((parent != null) ? parent.getId() : " null") + " value [" + value
        + "]");
    return str.toString();
  }

  /**
   * Creates a simple node and sets its value to the specified value.
   * 
   * @param value
   *          value. Can be null.
   */
  public SimpleNode(V value) {
    this.value = value;
    id = idGen.addAndGet(1);
  }

  @Override
  public List<Node<V>> getChildren() {
    if (this.children == null) {
      return Collections.emptyList();
    }
    return this.children;
  }

  @Override
  public int getId() {
    return this.id;
  }

  @Override
  public Node<V> getParent() {
    return this.parent;
  }

  @Override
  public V getValue() {
    return this.value;
  }

  @Override
  public void addChild(Node<V> node) {
    node.makeParent(this);
    if (this.children == null) {
      this.children = new ArrayList<Node<V>>();
    }
    this.children.add(node);
  }

  @Override
  public void makeParent(Node<V> parentNode) {
    if (this.getParent() != null) {
      throw new IllegalStateException("Cannot make node [" + parentNode
          + "] parent of current node [" + this
          + "], as current node already has a parent [" + this.parent + "]");
    }
    this.parent = parentNode;
  }
}
